<?php

namespace app\index\controller;

use AntCloudSDKCore\AntCloudClient;
use app\admin\model\Config;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Request;
use think\Session;
use think\Validate;

class Api extends Controller
{
    public function __construct()
    {
        $input = Request()->param();

        if (Request()->action() !== strtolower('executeConfirmGetOrderPlan')) {
            $token = $input[Config('key')];

            if (empty($token) || md5(date('Y/m/d') . Config('secret')) !== $token) apiReturn(2, '安全校验未通过');
        }
    }

    public function getVideoInfo()
    {
        $info = Db::name('video_info')->where(['id' => 1])->find();
        $info['img'] = getPicture($info['img']);
        $info['top_img'] = getPicture($info['top_img']);
        $order_count = Db::name('order')->where(['status' => 5])->count();
        $info['order_count'] = $order_count;
        $info['video_id'] = C('VIDEO_ID');

        apiReturn(1, '获取数据成功', $info);
    }

    /**
     * 获取openid
     * */
    public function getOpenid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(file_get_contents($url));

        apiReturn(1, '获取数据成功', $user_data);
    }

    /**
     * 微信登录
     * */
    public function wxLogin()
    {
        $input = Request()->param();

        $username = $input['username'];
        $avatar = $input['avatar'];
        $openid = $input['openid'];

        if (empty($openid)) apiReturn(2, '系统繁忙，请稍后再试~');

        $user_data = [
            'username' => $username,
            'avatar' => $avatar,
            'openid' => $openid,
            'create_time' => time(),
        ];

        $data = bindUser($openid, 0, $user_data);

        if ($data) {
            apiReturn(1, '登录成功', $data);
        } else {
            apiReturn(2, '登录失败');
        }
    }

    /**
     * 获取手机号
     * */
    public function getMobile()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $code = $input['code'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($code) || $code == 'undefined') apiReturn(2, 'code缺失');

        $token = get_access_token();
        if (empty($token)) apiReturn(2, 'TOKEN缺失');

        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token . '&code=' . $code;

        $data = [
            'code' => $code
        ];
        $result = httpsRequest($url, json_encode($data));
        $result = json_decode($result, true);

        if ($result['errcode'] == 0) {
            $mobile = $result['phone_info']['phoneNumber'];

            if ($mobile) {
                $count = Db::name('user')->where(['mobile' => $mobile])->count();
                if ($count > 0) apiReturn(2, '手机号码已存在');

                $update_user_data['mobile'] = $mobile;

                $user_info = Db::name('user')->field('level,up_user_id')->where(['id' => $user_id])->find();
                if ($user_info['level'] == 1 && $user_info['up_user_id'] > 0) {
                    $update_user_data['level'] = 2;

                    // 某个用户的级别变更需要将其所有上级都加入到用户升级的任务计划
                    addAllUpUserToUpPlan($user_id);
                }

                Db::name('user')->where(['id' => $user_id])->update($update_user_data);

                apiReturn(1, '获取数据成功', $mobile);
            } else {
                file_put_contents(RUNTIME_PATH . 'mobileErrGetMobile.txt', '手机号不存在===>' . json_encode($result, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
                apiReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            file_put_contents(RUNTIME_PATH . 'ApiErrGetMobile.txt', '时间：' . date('Y-m-d H:i:s') . '，用户ID：' . $user_id . ' ===> 错误码：' . $result['errcode'] . '；错误信息：' . $result['errmsg'] . '；code：' . $code . PHP_EOL, FILE_APPEND);
            if ($result['errcode'] == 40001) {
                apiReturn(2, '系统繁忙，请重新获取手机号');
            } elseif ($result['errcode'] == 40029) {
                apiReturn(3, '获取手机号失败，请前往【我 => 设置 => 关于微信】将微信版本更新至不低于8.0.16后，再回到此界面点击绑定手机');
            } else {
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }

    /**
     * 首页banner
     * */
    public function indexBanner()
    {
        $banner_list = Db::name('banner')->field('id,img,type,to_id')->select();

        if ($banner_list) {
            foreach ($banner_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $banner_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * banner文章详情
     * */
    public function bannerArticleDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '文章ID缺失');

        $info = Db::name('article')->field('id,title,content,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time']);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '文章不存在或已删除');
        }
    }

    /**
     * 商品分类
     * */
    public function goodsTypeList()
    {
        $list = Db::name('goods_type')->field('id,name')->where(['pid' => 0])->order('sort asc')->select();

        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 商品品牌
     * */
    public function goodsBrandList()
    {
        $list = Db::name('goods_brand')->field('id,name')->order('sort asc')->select();

        if ($list) {
            apiReturn(1, '获取数据成', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 商品列表
     * */
    public function goodsList()
    {
        $input = Request()->param();

        $name = $input['name'];
        $one_type_id = $input['one_type_id'] ? : 0;
        $sort = $input['sort'] ? : 0;//0：综合，1：销量，2：新品，3：价格
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        $where['upper'] = 1;

        if ($name) $where['name'] = ['LIKE', '%' . $name . '%'];
        if ($one_type_id) $where['one_type_id'] = $one_type_id;

        switch ($sort) {
            case 1:
                $order = 'sales_count desc';
                break;
            case 2:
                $order = 'create_time desc';
                break;
            case 3:
                $order = 'min_vip_price asc';
                break;
            default:
                $order = '';
                break;
        }

        $goods_list = Db::name('goods')->field('id,img,name,min_price,sales_count')->where($where)->order($order)->page($page, $pagesize)->select();
        if ($goods_list) {
            foreach ($goods_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $goods_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 分类列表
     * */
    /*public function goodsTypeList()
    {
        $list = Db::name('goods_type')->field('id,name,img,pid')->where(['pid' => 0])->select();
        if ($list) {
            foreach ($list as $k => &$v) {
                $son_list = Db::name('goods_type')->field('id,name,img,pid')->where(['pid' => $v['id']])->select();
                if ($son_list) {
                    foreach ($son_list as &$val) {
                        $val['img'] = getPicture($val['img']);
                    }
                }
                $v['son_list'] = $son_list;
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }*/

    /**
     * 商品列表
     * */
    /*public function goodsList()
    {
        $input = Request()->param();

        $two_type_id = $input['two_type_id'];
        $search_value = $input['search_value'];
        $one_type_id = $input['one_type_id'];
        $type = $input['type'] ? $input['type'] : 1;                       //排序；1：综合，2：销量，3：价格
        $price_sort = $input['price_sort'] ? $input['price_sort'] : 'desc';//价格排序；desc：降序，asc：升序
        $page = $input['page'] ? $input['page'] : 1;
        $pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

        if ($two_type_id) $where['two_type_id'] = $two_type_id;
        if ($search_value) $where['name'] = ['like', '%' . $search_value . '%'];
        switch ($type) {
            case 1:
                $order = 'create_time desc';
                break;
            case 2:
                $order = 'sales_count desc';
                break;
            case 3:
                $order = 'min_price ' . $price_sort;
        }

        if ($one_type_id) $where['one_type_id'] = $one_type_id;

        $list = Db::name('goods')->field('id,name,img,min_price')->where($where)->order($order)->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }*/

    /**
     * 商品详情
     * */
    public function goodsDetail()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];

        if (empty($id)) apiReturn(2, '商品ID缺失');

        $info = Db::name('goods')->field('id,name,img,poster,imgs,sales_count,desc_imgs,min_vip_price,min_price,content,user_instructions,product_param')->where(['id' => $id])->find();
        if ($info) {
            $info['img'] = getPicture($info['img']);
            $info['poster'] = getPicture($info['poster']);
            $info['imgs'] = doImgs($info['imgs']);
            $info['content'] = doEditorContent($info['content']);
            $info['product_param'] = json_decode($info['product_param'], true);
            $info['desc_imgs'] = doImgs($info['desc_imgs']);

            if ($user_id) {
                $user_info = Db::name('user')->field('username')->where(['id' => $user_id])->find();
                /*if (!$qr = $user_info['qr']) {
                    $qr = createUserQr($user_id);
                }
                $qr = getPicture($qr);
                $info['qr'] = $qr;*/

                $collect_count = Db::name('collect')->where(['to_id' => $id, 'user_id' => $user_id, 'status' => 1])->count();
                $info['collect_status'] = $collect_count ? true : false;

                $info['username'] = $user_info['username'];
            } else {
                $info['collect_status'] = false;
            }

            $sku_data = getSku($id);

            $info['sku_list'] = $sku_data['sku_list'];
            $info['sku_value_list'] = $sku_data['sku_value_list'];

            $comment_count = Db::name('goods_comment')->where(['goods_id' => $id])->count();
            $info['comment_count'] = $comment_count;

            //评价列表
            $comment_list = Db::name('goods_comment c')
                ->join('shop_user u', 'c.user_id = u.id', 'left')
                ->field('c.id,u.avatar,u.username,c.star,c.content,c.imgs,c.create_time')
                ->where(['c.goods_id' => $id])
                ->order('c.create_time desc')
                ->limit(2)
                ->select();
            if ($comment_list) {
                foreach ($comment_list as &$v) {
                    $v['username'] = cutUsername($v['username']);
                    $v['avatar'] = doAvatar($v['avatar']);
                    $v['imgs'] = doImgs($v['imgs']);
                    $v['star'] = intval($v['star']);
                    $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
                }
            } else {
                $comment_list = [];
            }
            $info['comment_list'] = $comment_list;

            // 服务保障
            $service_guarantee = Db::name('goods_service_guarantee')->value('service_guarantee');
            $service_guarantee_arr = json_decode($service_guarantee, true);
            $info['service_guarantee'] = $service_guarantee_arr;
            $info['service_guarantee_show'] = implode('·', array_column($service_guarantee_arr, 'param'));

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '商品不存在或已删除');
        }
    }

    /**
     * 商品分享信息
     * */
    public function goodsShare()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $goods_id = $input['goods_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($goods_id)) apiReturn(2, '商品ID缺失');

        $info = Db::name('goods')->field('id,poster,name,min_vip_price,min_price,sales_count')->where(['id' => $goods_id])->find();
        if ($info) {
            $info['poster'] = getPicture($info['poster']);

            $user_info = Db::name('user')->field('qr,level')->where(['id' => $user_id])->find();
            /*if (!$qr = $user_info['qr']) {
                $qr = createUserQr($user_id);
            }
            $qr = getPicture($qr);
            $info['qr'] = $qr;*/

            $info['price'] = $user_info['level'] > 1 ? $info['min_vip_price'] : $info['min_price'];

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 收藏/取消收藏
     * */
    public function doCollect()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $to_id = $input['to_id'];
        $type = $input['type'];    //1：商品
        $status = $input['status'];//0：取消收藏，1：收藏

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($to_id)) apiReturn(2, '收藏对象ID缺失');

        $time = time();

        $info = Db::name('collect')->where(['user_id' => $user_id, 'to_id' => $to_id, 'type' => $type])->find();
        if ($info) {
            $data = [
                'status' => $status,
                'update_time' => $time,
                'create_time' => $time
            ];
            $res = Db::name('collect')->where(['id' => $info['id']])->update($data);
            $msg = $status == 0 ? '取消收藏' : '收藏';
            if ($res) {
                apiReturn(1, $msg . '成功');
            } else {
                apiReturn(2, $msg . '失败');
            }
        } else {
            if ($status == 0) {
                apiReturn(2, '系统繁忙，请稍后再试~');
            } else {
                $data = [
                    'user_id' => $user_id,
                    'to_id' => $to_id,
                    'type' => $type,
                    'status' => $status,
                    'create_time' => $time
                ];
                $res = Db::name('collect')->insert($data);
                if ($res) {
                    apiReturn(1, '收藏成功');
                } else {
                    apiReturn(2, '收藏失败');
                }
            }
        }
    }

    /**
     * 商品评价列表
     * */
    public function goodsCommentList()
    {
        $input = Request()->param();

        $id = $input['id'];
        $page = $input['page'] ? $input['page'] : 1;
        $pagesize = $input['pagesize'] ? $input['pagesize'] : 10;

        if (empty($id)) apiReturn(2, '商品ID缺失');

        $list = Db::name('goods_comment c')
            ->join('shop_user u', 'c.user_id = u.id', 'left')
            ->field('c.id,u.avatar,u.username,c.star,c.content,c.imgs,c.create_time')
            ->where(['c.goods_id' => $id])
            ->order('c.create_time desc')
            ->page($page, $pagesize)
            ->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['username'] = cutUsername($v['username']);
                $v['avatar'] = doAvatar($v['avatar']);
                $v['imgs'] = doImgs($v['imgs']);
                $v['star'] = intval($v['star']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 购物车商品数量校正
     * tips：在小程序 onHide 和 onUnload 中调用该接口
     * */
    public function doCarGoodsCount()
    {
        $input = Request()->param();;
        $car_list = json_decode($input['car_list'], true);//[{"id":"4","count":"8"}]
        if ($car_list) {
            foreach ($car_list as &$v) {
                Db::name('goods_car')->where(['id' => $v['id']])->setField('count', $v['count']);
            }
        }
    }

    /**
     * 加入购物车
     * */
    public function addGoodsCar()
    {
        $input = Request()->param();;

        $id = $input['id'];//商品id
        $user_id = $input['user_id'];
        $sku_id = $input['sku_id'];//属性id组合；sku_value表sku_id
        $count = $input['count'];

        if (empty($id)) apiReturn(2, '商品ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if ($count <= 0) apiReturn(2, '商品数量异常');


        $user_level = Db::name('user')->where(['id' => $user_id])->value('level');

        $goods_info = Db::name('goods')->where(['id' => $id])->find();
        if ($goods_info) {
            $sku_info = Db::name('sku_value')->field('sku_id,img,vip_price,price,stock')->where(['sku_id' => $sku_id, 'goods_id' => $id])->find();
            if ($sku_info) {
                if ($sku_info['stock'] < $count) apiReturn(2, '商品所选属性库存不足');

                $car_info = Db::name('goods_car')->where(['user_id' => $user_id, 'goods_id' => $id, 'sku_id' => $sku_id])->find();
                if ($car_info) {
                    //该商品之前已经加入过购物车，这个时候只需要增加购物车数量即可
                    $res = Db::name('goods_car')->where(['id' => $car_info['id']])->setInc('count', $count);
                } else {
                    //该商品第一次加入购物车，添加购物车数据
                    $data = [
                        'user_id' => $user_id,
                        'goods_id' => $id,
                        'img' => $sku_info['img'],
                        'sku_id' => $sku_info['sku_id'],
                        'count' => $count,
                        'price' => $sku_info['price'],
                        'create_time' => time()
                    ];
                    $res = Db::name('goods_car')->insert($data);
                }
            } else {
                apiReturn(2, '属性不存在或已删除');
            }

            if ($res) {
                apiReturn(1, '添加成功');
            } else {
                apiReturn(2, '添加购物车失败');
            }
        } else {
            apiReturn(2, '商品不存在或已删除');
        }
    }

    /**
     * 购物车列表
     * */
    public function goodsCarList()
    {
        $input = Request()->param();;

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('goods_car')->where(['user_id' => $user_id])->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
                $goods_info = Db::name('goods')->where(['id' => $v['goods_id']])->find();
                $v['goods_name'] = $goods_info['name'];
                $v['actived'] = false;

                if ($sku_list = getSkuName(explode('-', $v['sku_id']))) $v['sku'] = implode('，', array_column($sku_list, 'name'));
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无数据');
        }
    }

    /**
     * 移除购物车商品
     * */
    public function removeGoodsCar()
    {
        $input = Request()->param();;
        $car_ids = $input['car_ids'];
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
        $res = Db::name('goods_car')->where(['id' => ['IN', $car_ids]])->delete();
        if ($res) {
            apiReturn(1, '移除成功');
        } else {
            apiReturn(2, '移除失败');
        }
    }

    /**
     * 购物车订单确认页
     * */
    public function goodsCarOrderConfirm()
    {
        $input = Request()->param();
        $user_id = $input['user_id'];
        $car_ids = $input['car_ids'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

        $car_list = Db::name('goods_car')->field('id,goods_id,img,sku_id,price,count')->where(['id' => ['IN', $car_ids]])->select();
        $all_price = 0;
        if ($car_list) {
            foreach ($car_list as &$v) {
                $goods_info = Db::name('goods')->field('name,gift_ids')->where(['id' => $v['goods_id']])->find();
                $v['goods_name'] = $goods_info['name'];
                $v['img'] = getPicture($v['img']);
                $v['sku'] = implode('，', array_column(getSkuName(explode('-', $v['sku_id'])), 'name'));
                $all_price += sprintf("%.2f", $v['price'] * $v['count']);

                $gift_list = [];
                $full_price_send_gift = C('FULL_PRICE_SEND_GIFT');
                /**
                 * 复消一次性消费累计达到N元，社区服务站及以上送赠品，且按N的倍数增加赠送数量
                 * tips:
                 * 复消：用户该次消费时处于已激活状态，说明该次为复消
                 * */
                if ($goods_info['gift_ids'] && $user_info['level'] >= 3 && $user_info['is_activation'] == 1 && $full_price_send_gift <= $v['price'] * $v['count']) {
                    $gift_list = Db::name('goods_gift')->field('id,gift_img,gift_name,gift_price')->where(['id' => ['IN', $goods_info['gift_ids']], 'is_del' => 0, 'start_date' => ['elt', date('Y-m-d')], 'end_date' => ['egt', date('Y-m-d')]])->select();
                    if ($gift_list) {
                        foreach ($gift_list as &$val) {
                            $val['gift_img'] = getPicture($val['gift_img']);
                        }
                    }
                    $v['gift_list'] = $gift_list;
                }
            }
            //默认收货地址
            $address_info = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address')->where(['user_id' => $user_id, 'is_default' => 1])->find();
            if ($address_info) {
                $address_info['address'] = getProvinceName($address_info['province_id']) . getCityName($address_info['city_id']) . getAreaName($address_info['area_id']) . $address_info['address'];
            }

            //优惠券列表
            $empty_coupon = [
                [
                    'id' => 0,
                    'coupon_name' => '请选择优惠券',
                    'full_price' => 0,
                    'face_price' => 0
                ]
            ];
            $coupon_list = Db::name('user_coupon')->field('id,coupon_name,full_price,face_price')->where(['user_id' => $user_id, 'is_del' => 0, 'full_price' => ['elt', $all_price], 'status' => 1])->order('expire_time asc')->select();

            // 运费模板信息
            $freight_info = Db::name('freight')->field('id,init_count,init_count_price,inc_count,inc_count_price,diff_freight')->where(['type' => 1])->find();

            // 当前可用收益
            $profit = Db::name('user')->where(['id' => $user_id])->value('all_profit');

            $data = [
                'goods_list' => $car_list,
                'all_price' => sprintf('%.2f', $all_price),
                'address' => $address_info ? : [],
                'freight_info' => $freight_info,
                'coupon_list' => $coupon_list ? array_merge($empty_coupon, $coupon_list) : $empty_coupon,
                'profit' => $profit
            ];
            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '购物车商品数据异常');
        }
    }

    /**
     * 购物车立即支付【生成待支付订单】 之后 发起支付
     * */
    public function addGoodsCarOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $car_ids = $input['car_ids'];
        $coupon_id = $input['coupon_id'];
        $all_price = $input['all_price'];
        $freight_price = $input['freight_price'] ? : 0;
        $pay_price = $input['pay_price'];
        $address_id = $input['address_id'];
        $pay_type = $input['pay_type'];
        $remark = $input['remark'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($car_ids)) apiReturn(2, '购物车ID缺失');
        if (empty($all_price) || empty($pay_price)) apiReturn(2, '商品金额错误');
        if (empty($address_id)) apiReturn(2, '请选择收货地址');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

        $time = time();

        Db::startTrans();
        try {
            $car_list = Db::name('goods_car')->field('id,goods_id,price,sku_id,count')->where(['id' => ['IN', $car_ids]])->select();

            if ($car_list) {
                $address_info = Db::name('address')->where(['id' => $address_id])->find();
                foreach ($car_list as &$v) {
                    $goods_info = Db::name('goods')->field('id,name,gift_ids')->where(['id' => $v['goods_id']])->find();

                    $sku_info = Db::name('sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->find();
                    if ($sku_info) {
                        if ($v['count'] > $sku_info['stock']) apiReturn(2, $goods_info['name'] . '库存不足');
                    } else {
                        apiReturn(2, $goods_info['name'] . '属性不存在或已删除');
                    }

                    // 复购才有赠品
                    $gift_list = [];
                    $full_price_send_gift = C('FULL_PRICE_SEND_GIFT');
                    /**
                     * 复消一次性消费累计达到N元，社区服务站及以上送赠品，且按N的倍数增加赠送数量
                     * tips:
                     * 复消：用户该次消费时处于已激活状态，说明该次为复消
                     * */
                    if ($goods_info['gift_ids'] && $user_info['level'] >= 3 && $user_info['is_activation'] == 1 && $full_price_send_gift <= $v['price'] * $v['count']) $gift_list = Db::name('goods_gift')->field('id')->where(['id' => ['IN', $goods_info['gift_ids']], 'is_del' => 0, 'start_date' => ['elt', date('Y-m-d')], 'end_date' => ['egt', date('Y-m-d')]])->select();
                    $gift_ids = $gift_list ? implode(',', array_column($gift_list, 'id')) : '';

                    $sku_info = Db::name('sku_value')->where(['goods_id' => $v['goods_id'], 'sku_id' => $v['sku_id']])->find();
                    $goods_order[] = [
                        'goods_id' => $v['goods_id'],
                        'img' => $sku_info['img'],
                        'name' => $goods_info['name'],
                        'sku_id' => $sku_info['sku_id'],
                        'price' => $user_info['level'] > 1 ? $sku_info['vip_price'] : $sku_info['price'],
                        'count' => $v['count'],
                        'gift_ids' => $gift_ids,
                        'create_time' => $time
                    ];
                }

                //订单主表添加数据
                $order_sn = createOrderSn();
                $order_data = [
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'pay_order_sn' => $order_sn,
                    'coupon_id' => $coupon_id,
                    'all_price' => $all_price,
                    'freight_price' => $freight_price,
                    'pay_price' => $pay_price,
                    'get_username' => $address_info['username'],
                    'get_mobile' => $address_info['mobile'],
                    'get_province' => getProvinceName($address_info['province_id']),
                    'get_city' => getCityName($address_info['city_id']),
                    'get_area' => getAreaName($address_info['area_id']),
                    'get_address' => $address_info['address'],
                    'up_user_id' => $user_info['up_user_id'],
                    'is_first_order' => $user_info['is_activation'] ? 0 : 1,
                    'is_valid' => $user_info['level'] > 1 ? 1 : 0,
                    'pay_type' => $pay_type,
                    'remark' => $remark,
                    'car_ids' => $car_ids,
                    'create_time' => $time
                ];
                $order_id = Db::name('order')->insertGetId($order_data);

                if ($goods_order) {
                    foreach ($goods_order as &$v) {
                        $v['order_id'] = $order_id;
                    }
                } else {
                    apiReturn(2, '订单信息错误');
                }
                $vice_order_res = Db::name('vice_order')->insertAll($goods_order);

                if ($order_id && $vice_order_res) {
                    // 清除对应购物车商品
                    Db::name('goods_car')->where(['id' => ['IN', $car_ids]])->delete();

                    if ($pay_type == 1) {
                        //微信支付
                        Loader::import('wxpaysdk\wxPay', EXTEND_PATH);
                        $obj = new \wxPay();

                        $pay_price = 0.01;
                        //调用示例（最后两个参数为可选参数）
                        $pay_data = $obj->jsApi($user_info['openid'], $pay_price, $order_sn, '商品支付', getHost() . '/Index/Notify/notice');

                        $return_data = [
                            'pay_data' => $pay_data,
                        ];
                    } else {
                        //收益支付

                        if ($pay_price > 0) {
                            //新增购物收益抵扣记录
                            $profit_data = [
                                'order_id' => $order_id,
                                'user_id' => $user_id,
                                'price' => $pay_price,
                                'type' => 4,
                                'status' => 2,
                                'create_time' => $time
                            ];
                            Db::name('profit')->insert($profit_data);

                            $find_user_id = Db::name('order')->where(['id' => $order_id])->value('user_id');
                            if ($find_user_id) {
                                $find_user_info = Db::name('user')->field('username,mobile')->where(['id' => $find_user_id])->find();
                                $mobile = $find_user_info['mobile'];
                            }

                            // 扣除用户收益
                            Db::name('user')->where(['id' => $user_id])->setDec('all_profit', $pay_price);

                            // 发送微信公众号模板消息
                            $template_msg = [
                                'first' => [
                                    'value' => '您好，您成功使用' . $pay_price . '收益购物',
                                    'color' => '#743A3A'
                                ],
                                'keyword1' => [
                                    'value' => '购物收益抵扣',
                                    'color' => '#743A3A'
                                ],
                                'keyword2' => [
                                    'value' => '-' . $pay_price,
                                    'color' => '#743A3A'
                                ],
                                'keyword3' => [
                                    'value' => date('Y-m-d'),
                                    'color' => '#743A3A'
                                ],
                                'keyword4' => [
                                    'value' => '点击查看',
                                    'color' => '#743A3A'
                                ],
                                'remark' => [
                                    'value' => '',
                                    'color' => '#743A3A'
                                ]
                            ];
                            $page = 'pages/my_income/my_income';
                            if ($user_info['gzh_openid']) sendWxTemplateNotice($user_info['gzh_openid'], $template_msg, 4, $page);

                            sleep(1);
                        }

                        action('Index/Notify/doOrder', $order_sn);
                    }

                    Db::commit();
                    apiReturn(1, '获取数据成功', $return_data ? : []);
                } else {
                    Db::rollback();
                    apiReturn(2, '订单生成失败');
                }
            } else {
                Db::rollback();
                apiReturn(2, '购物车商品数据异常');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试');
        }
    }

    /**
     * 商品确认订单
     * */
    public function confirmOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $goods_id = $input['goods_id'];
        $sku_id = $input['sku_id'];
        $count = $input['count'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($goods_id)) apiReturn(2, '商品ID缺失');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if (empty($count)) apiReturn(2, '商品数量异常');

        $sku_list = Db::name('sku_value')->field('sku_id,img,price,vip_price,goods_id')->where(['sku_id' => $sku_id, 'goods_id' => $goods_id])->select();
        if ($sku_list) {
            foreach ($sku_list as &$v) {
                $goods_info = Db::name('goods')->field('name,gift_ids')->where(['id' => $v['goods_id']])->find();
                $v['goods_name'] = $goods_info['name'];
                $v['img'] = getPicture($v['img']);
                $v['sku'] = implode('，', array_column(getSkuName(explode('-', $v['sku_id'])), 'name'));
                $all_price = sprintf("%.2f", (($v['price']) * $count));
            }

            //默认收货地址
            $default_address = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address')->where(['user_id' => $user_id])->order('is_default desc,id desc')->find();
            if ($default_address) {
                $default_address['address'] = getProvinceName($default_address['province_id']) . getCityName($default_address['city_id']) . getAreaName($default_address['area_id']) . $default_address['address'];
            }

            //优惠券列表
            $empty_coupon = [
                [
                    'id' => 0,
                    'coupon_name' => '请选择优惠券',
                    'full_price' => 0,
                    'face_price' => 0
                ]
            ];
            $coupon_list = Db::name('user_coupon')->field('id,coupon_name,full_price,face_price')->where(['user_id' => $user_id, 'is_del' => 0, 'full_price' => ['elt', $all_price], 'status' => 1])->order('expire_time asc')->select();

            // 运费模板信息
            $freight_info = Db::name('freight')->field('id,init_count,init_count_price,inc_count,inc_count_price,diff_freight')->where(['type' => 1])->find();

            // 当前可用收益
            $profit = Db::name('user')->where(['id' => $user_id])->value('all_profit');

            $data = [
                'goods_list' => $sku_list,
                'all_price' => $all_price,
                'address' => $default_address ? : [],
                'freight_info' => $freight_info,
                'coupon_list' => $coupon_list ? array_merge($empty_coupon, $coupon_list) : $empty_coupon,
                'profit' => $profit
            ];

            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '规格不存在或已删除');
        }
    }

    /**
     * 立即支付【生成待支付订单】 之后 发起支付
     * */
    public function addGoodsOrder()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $goods_id = $input['goods_id'];
        $count = $input['count'];
        $sku_id = $input['sku_id'];
        $coupon_id = $input['coupon_id'];
        $all_price = $input['all_price'];
        $pay_price = $input['pay_price'];
        $address_id = $input['address_id'];
        $freight_price = $input['freight_price'];
        $pay_type = $input['pay_type'];
        $remark = $input['remark'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($goods_id)) apiReturn(2, '商品ID缺失');
        if ($count <= 0) apiReturn(2, '商品数量异常');
        if (empty($sku_id)) apiReturn(2, '属性ID缺失');
        if (empty($all_price) || empty($pay_price)) apiReturn(2, '商品金额错误');
        if (empty($address_id)) apiReturn(2, '请选择收货地址');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if (empty($user_info)) apiReturn(2, '用户信息不存在或已删除');

        $time = time();

        Db::startTrans();
        try {
            $goods_info = Db::name('goods')->field('id,name,gift_ids')->where(['id' => $goods_id])->find();
            if ($goods_info) {
                $sku_info = Db::name('sku_value')->where(['sku_id' => $sku_id, 'goods_id' => $goods_id])->find();
                if ($sku_info) {
                    //商品库存
                    if ($count > $sku_info['stock']) apiReturn(2, '商品库存不足');

                    $address_info = Db::name('address')->where(['id' => $address_id])->find();

                    $user_level = $user_info['level'];

                    $order_sn = createOrderSn();
                    $data = [
                        'user_id' => $user_id,
                        'order_sn' => $order_sn,
                        'pay_order_sn' => $order_sn,
                        'coupon_id' => $coupon_id,
                        'all_price' => $all_price,
                        'freight_price' => $freight_price,
                        'pay_price' => $pay_price,
                        'get_username' => $address_info['username'],
                        'get_mobile' => $address_info['mobile'],
                        'get_province' => getProvinceName($address_info['province_id']),
                        'get_city' => getCityName($address_info['city_id']),
                        'get_area' => getAreaName($address_info['area_id']),
                        'get_address' => $address_info['address'],
                        'up_user_id' => $user_info['up_user_id'],
                        'is_first_order' => $user_info['is_activation'] ? 0 : 1,
                        'pay_type' => $pay_type,
                        'remark' => $remark,
                        'is_valid' => $user_level > 1 ? 1 : 0,
                        'create_time' => $time
                    ];

                    $order_id = Db::name('order')->insertGetId($data);

                    $gift_list = [];
                    $full_price_send_gift = C('FULL_PRICE_SEND_GIFT');
                    /**
                     * 复消一次性消费累计达到N元，社区服务站及以上送赠品，且按N的倍数增加赠送数量
                     * tips:
                     * 复消：用户该次消费时处于已激活状态，说明该次为复消
                     * */
                    if ($goods_info['gift_ids'] && $user_info['level'] >= 3 && $user_info['is_activation'] == 1 && $full_price_send_gift <= $all_price) $gift_list = Db::name('goods_gift')->field('id')->where(['id' => ['IN', $goods_info['gift_ids']], 'is_del' => 0, 'start_date' => ['elt', date('Y-m-d')], 'end_date' => ['egt', date('Y-m-d')]])->select();
                    $gift_ids = $gift_list ? implode(',', array_column($gift_list, 'id')) : '';

                    $goods_order = [
                        'order_id' => $order_id,
                        'goods_id' => $goods_id,
                        'img' => $sku_info['img'],
                        'name' => $goods_info['name'],
                        'sku_id' => $sku_id,
                        'price' => $sku_info['price'],
                        'count' => $count,
                        'gift_ids' => $gift_ids,
                        'create_time' => $time
                    ];
                    Db::name('vice_order')->insert($goods_order);

                    if ($pay_type == 1) {
                        //微信支付
                        Loader::import('wxpaysdk\wxPay', EXTEND_PATH);
                        $obj = new \wxPay();
                        //调用示例（最后两个参数为可选参数）
                        $pay_price = 0.01;
                        $pay_data = $obj->jsApi($user_info['openid'], $pay_price, $order_sn, '商品支付', getHost() . '/Index/Notify/notice');

                        $return_data = [
                            'pay_data' => $pay_data,
                            'order_id' => $order_id
                        ];
                    } else {
                        //收益支付
                        if ($pay_price) {
                            //新增购物收益抵扣记录
                            $profit_data = [
                                'order_id' => $order_id,
                                'user_id' => $user_id,
                                'price' => $pay_price,
                                'type' => 4,
                                'status' => 2,
                                'create_time' => $time
                            ];
                            Db::name('profit')->insert($profit_data);

                            $find_user_id = Db::name('order')->where(['id' => $order_id])->value('user_id');
                            if ($find_user_id) {
                                $find_user_info = Db::name('user')->field('username,mobile')->where(['id' => $find_user_id])->find();
                                $mobile = $find_user_info['mobile'];
                            }

                            // 扣除用户收益
                            Db::name('user')->where(['id' => $user_id])->setDec('all_profit', $pay_price);

                            // 发送微信公众号模板消息
                            /*$template_msg = [
                                'first' => [
                                    'value' => '您好，您成功使用' . $pay_price . '收益购物',
                                    'color' => '#743A3A'
                                ],
                                'keyword1' => [
                                    'value' => '购物收益抵扣',
                                    'color' => '#743A3A'
                                ],
                                'keyword2' => [
                                    'value' => '-' . $pay_price,
                                    'color' => '#743A3A'
                                ],
                                'keyword3' => [
                                    'value' => date('Y-m-d'),
                                    'color' => '#743A3A'
                                ],
                                'keyword4' => [
                                    'value' => '点击查看',
                                    'color' => '#743A3A'
                                ],
                                'remark' => [
                                    'value' => '',
                                    'color' => '#743A3A'
                                ]
                            ];
                            $page = 'pages/my_income/my_income';
                            if ($user_info['gzh_openid']) sendWxTemplateNotice($user_info['gzh_openid'], $template_msg, 4, $page);

                            sleep(1);*/
                        }

                        action('Index/Notify/doOrder', $order_sn);
                    }

                    Db::commit();
                    apiReturn(1, '获取数据成功', $return_data);
                } else {
                    Db::rollback();
                    apiReturn(2, '规格不存在或已删除');
                }
            } else {
                Db::rollback();
                apiReturn(2, '商品不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试');
        }
    }

    /**********************订单列表接口   START**********************/
    /**
     * 取消订单
     * */
    public function cancelOrder()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id, 'is_del' => 0])->find();
        if ($info) {
            $data = [
                'status' => 10,
                'update_time' => time()
            ];
            $res = Db::name('order')->where(['id' => $id])->update($data);
            if ($res) {
                apiReturn(1, '订单取消成功');
            } else {
                apiReturn(2, '订单取消失败');
            }
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 订单列表立即支付
     * */
    public function payNow()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        Db::startTrans();
        try {
            $info = Db::name('order')->where(['id' => $id, 'is_del' => 0])->find();
            if ($info) {
                $pay_order_sn = 'PAY' . date('y') . date('m') . date('d') . date('H') . date('i') . rand(1000, 9999);
                Db::name('order')->where(['id' => $id])->setField('pay_order_sn', $pay_order_sn);

                $openid = Db::name("user")->where(['id' => $info['user_id']])->value("openid");

                Loader::import('wxpaysdk\wxPay', EXTEND_PATH);
                $obj = new \wxPay();
                //调用示例（最后两个参数为可选参数）
                $info['pay_price'] = 0.01;
                $pay_data = $obj->jsApi($openid, $info['pay_price'], $pay_order_sn, '商品支付', getHost() . '/Index/Notify/notice');

                if ($pay_data) {
                    Db::commit();
                    apiReturn(1, '获取支付信息成功', $pay_data);
                } else {
                    Db::rollback();
                    apiReturn(2, '系统繁忙，请稍后再试~');
                }
            } else {
                Db::rollback();
                apiReturn(2, '订单不存在或已删除');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 申请售后页面数据
     */
    public function afterData()
    {
        $after_type = ['退货退款', '换货'];

        $after_reason = C('AFTER_REASON');

        $data = [
            'after_type' => $after_type,
            'after_reason' => $after_reason
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 申请售后
     */
    public function applyAfter()
    {
        $input = Request()->param();

        $id = $input['id'];
        $after_type = $input['after_type'];
        $after_reason = $input['after_reason'];
        $after_desc = $input['after_desc'];

        if (empty($id)) apiReturn(2, '订单ID不存在');
        if (empty($after_type)) apiReturn(2, '请选择申请类型');
        if (empty($after_reason)) apiReturn(2, '请选择原因');
        if (empty($after_desc)) apiReturn(2, '请填写说明描述');

        $info = Db::name('order')->where(['id' => $id])->find();
        if (empty($info)) apiReturn(2, '订单不存在或已删除');

        $data = [
            'status' => 7,
            'after_type' => $after_type,
            'after_reason' => $after_reason,
            'after_desc' => $after_desc,
            'update_time' => time()
        ];

        $res = Db::name('order')->where(['id' => $id])->update($data);
        if ($res) {
            Db::name('plan')->where(['order_id' => $id, 'type' => 2])->delete();

            apiReturn(1, '申请成功');
        } else {
            apiReturn(2, '申请失败');
        }
    }

    /**
     * 物流信息
     * */
    public function queryExpress()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id])->find();
        if (empty($info)) apiReturn(2, '订单不存在或已删除', []);

        Db::startTrans();
        try {
            $express_info = Db::name('express')->where(['id' => $info['express_id']])->find();
            $code = $express_info['code'];

            $num = $info['send_num'];
            $mobile = $info['get_mobile'];

            $log_info = Db::name('express_log')->where(['code' => $code, 'num' => $num, 'mobile' => $mobile])->find();
            if ($log_info) {
                if ($log_info['update_time'] > time() - 30 * 60) {
                    //距离上次查询未超过半小时，直接获取记录当中的快递信息
                    $data = json_decode($log_info['result'], true);
                } else {
                    $data = $this->query($code, $num, $mobile);
                    //更新快递查询信息
                    Db::name('express_log')->where(['code' => $code, 'num' => $num, 'mobile' => $mobile])->setField('update_time', time());
                }
            } else {
                $data = $this->query($code, $num, $mobile);

                if ($data) {
                    //新增快递查询信息
                    $log_data = [
                        'code' => $code,
                        'num' => $num,
                        'mobile' => $mobile,
                        'result' => json_encode($data, JSON_UNESCAPED_UNICODE),
                        'update_time' => time()
                    ];
                    Db::name('express_log')->insert($log_data);
                }
            }

            if (empty($info['express_id'])) {
                Db::rollback();
                apiReturn(2, '快递公司信息缺失');
            }

            $express_name = Db::name('express')->where(['id' => $info['express_id']])->value('name');

            $info = [
                'express_name' => $express_name,
                'send_num' => $info['send_num'],
                'list' => $data['data']
            ];

            Db::commit();
            apiReturn(1, '获取数据成功', $info);
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~' . $e);
        }
    }

    public function query($code, $num, $mobile)
    {
        Loader::import('kuaidi100\Express', EXTEND_PATH);

        $obj = new \Express();

        $result = $obj->synquery($code, $num, $mobile);

        return json_decode(json_encode($result, JSON_UNESCAPED_UNICODE), true);
    }

    /**
     * 确认收货
     * */
    public function confirmGetGoods()
    {
        $input = Request()->param();
        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->where(['id' => $id, 'is_del' => 0])->find();

        if ($info['status'] != 3) apiReturn(2, '订单状态非待收货，确认收货失败');

        if ($info) {
            Db::startTrans();
            try {
                $time = time();
                $order_data = [
                    'status' => 4,
                    'update_time' => $time,
                    'complete_time' => $time
                ];
                Db::name('order')->where(['id' => $id])->update($order_data);

                // 收益解冻（直推收益，级差收益，服务津贴）
                $profit_data = [
                    'status' => 2,
                    'update_time' => $time
                ];
                Db::name('profit')->where(['order_id' => $id, 'type' => ['IN', [1, 2, 3]]])->update($profit_data);

                $profit_list = Db::name('profit')->where(['order_id' => $id, 'type' => ['IN', [1, 2, 3]]])->select();
                if ($profit_list) {
                    foreach ($profit_list as &$v) {
                        Db::name('user')->where(['id' => $v['user_id']])->setInc('all_profit', $v['price']);
                        file_put_contents(RUNTIME_PATH . 'confirmGetSql.txt', Db::name('user')->getLastSql() . PHP_EOL, FILE_APPEND);
                    }
                }

                // 游客下单后变成VIP
                $level = Db::name('user')->where(['id' => $info['user_id']])->value('level');
                if ($level < 2) Db::name('user')->where(['id' => $info['user_id']])->setField('level', 2);

                Db::name('user')->where(['id' => $info['user_id']])->setInc('all_consume', $info['pay_price']);

                // 任务表新增 （用户 会员等级/档数 升级）任务  ==> 当前用户以及所有上级用户
                if ($user_id = $info['user_id']) {
                    // 某个用户的级别变更需要将其所有上级都加入到用户升级的任务计划
                    addAllUpUserToUpPlan($user_id, true);
                }

                // 确认收货之后删除任务表 【确认收货】 任务
                Db::name('plan')->where(['order_id' => $id, 'type' => 2])->delete();

                Db::commit();
                apiReturn(1, '确认收货成功');
            } catch (\Exception $e) {
                Db::rollback();
                apiReturn(2, '系统繁忙，请稍后再试~' . $e);
            }
        } else {
            apiReturn(2, '订单信息不存在或已删除');
        }
    }

    /**
     * 商品评价回显数据
     * */
    public function orderGoodsList()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $goods_list = Db::name('vice_order')->field('id,order_id,goods_id,img,name,sku_id,price,count')->where(['order_id' => $id])->select();
        if ($goods_list) {
            foreach ($goods_list as &$val) {
                $val['img'] = getPicture($val['img']);
                if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
            }

            apiReturn(1, '获取数据成功', $goods_list);
        } else {
            apiReturn(2, '订单商品数据不存在或已删除');
        }
    }

    /**
     * 商品评价
     * */
    public function goodsComment()
    {
        $input = Request()->param();

        $comment_list = $input['comment_list'];

        Db::startTrans();
        try {
            $time = time();
            if ($comment_list) {
                $have_empty = false;
                $data = [];
                foreach ($comment_list as &$v) {
                    if (empty($v['content'])) {
                        $have_empty = true;
                        break;
                    } else {
                        checkContent($v['content']);

                        $data[] = [
                            'user_id' => $v['user_id'],
                            'order_id' => $v['order_id'],
                            'vice_order_id' => $v['vice_order_id'],
                            'goods_id' => $v['goods_id'],
                            'star' => $v['star'],
                            'content' => $v['content'],
                            'imgs' => $v['imgs'],
                            'create_time' => $time
                        ];
                    }
                }

                if ($have_empty) apiReturn(2, '请针对所有商品作出评价');

                Db::name('goods_comment')->insertAll($data);

                $order_id = Db::name('vice_order')->where(['id' => $comment_list[0]['vice_order_id']])->value('order_id');
                $order_data = [
                    'status' => 5,
                    'update_time' => $time
                ];
                Db::name('order')->where(['id' => $order_id])->update($order_data);

                Db::commit();
                apiReturn(1, '评价成功');
            } else {
                Db::rollback();
                apiReturn(2, '评价数据出错，请稍后再试~');
            }
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**********************订单列表接口   END**********************/

    /**
     * 最新消息
     * */
    public function newMsgList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        // 分页起始位置
        $offset = ($page - 1) * $pagesize;
        // 未读信息条件
        $where = '(user_id = ' . $user_id . ' or user_id = 0)';
        // 未读
        $sql = 'select id,order_id,title,content,read_user,type,create_time from shop_msg where ' . $where . ' order by find_in_set(read_user, ' . $user_id . '),create_time desc limit ' . $offset . ', ' . $pagesize;
        $list = Db::name('msg')->query($sql);
        if ($list) {
            foreach ($list as &$v) {
                $v['is_read'] = in_array($user_id, explode(',', $v['read_user'])) ? true : false;
                $v['content'] = doEditorContent($v['content']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 分类消息列表
     * */
    public function msgList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $type = $input['type'] ? : 1;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        // 分页起始位置
        $offset = ($page - 1) * $pagesize;
        // 未读信息条件
        $where = '(user_id = ' . $user_id . ' or user_id = 0) and type = ' . $type;
        // 未读
        $sql = 'select id,order_id,title,content,read_user,type,create_time from shop_msg where ' . $where . ' order by find_in_set(read_user, ' . $user_id . '),create_time desc limit ' . $offset . ', ' . $pagesize;
        $list = Db::name('msg')->query($sql);
        if ($list) {
            foreach ($list as &$v) {
                $v['is_read'] = in_array($user_id, explode(',', $v['read_user'])) ? true : false;
                $v['content'] = doEditorContent($v['content']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y.m.d H:i');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 消息详情
     * */
    public function msgDetail()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];

        if (empty($id)) apiReturn(2, '消息ID缺失');
        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $info = Db::name('msg')->field('id,title,content,read_user,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['create_time'] = timeFormat($info['create_time'], 'Y.m.d H:i');

            Db::name('msg')->where(['id' => $id])->setInc('look_count');

            $is_read = in_array($user_id, explode(',', $info['read_user'])) ? true : false;
            if (!$is_read) Db::name('msg')->where(['id' => $id])->setField('read_user', $info['read_user'] ? $info['read_user'] . ',' . $user_id : $user_id);

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '消息不存在或已删除');
        }
    }

    /**
     * 收货地址列表
     * */
    public function addressList()
    {
        $input = Request()->param();
        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address,is_default')->where(['user_id' => $user_id])->order('is_default desc,create_time desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['province'] = getProvinceName($v['province_id']);
                $v['city'] = getCityName($v['city_id']);
                $v['area'] = getAreaName($v['area_id']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无收货地址', []);
        }
    }

    /**
     * 个人中心
     * */
    public function userCenter()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $info = Db::name('user')->field('id,avatar,username,level user_level,gear,all_profit,status')->where(['id' => $user_id])->find();
        if ($info) {
            //用户被禁用提示语
            $info['user_disable_msg'] = C('USER_DISABLE_MSG');

            $info['level'] = doUserLevel($info['user_level']);
            $info['avatar'] = doAvatar($info['avatar']);

            switch ($info['gear']) {
                case 'first_gear':
                    $info['gear'] = 1;
                    break;
                case 'second_gear':
                    $info['gear'] = 2;
                    break;
                case 'third_gear':
                    $info['gear'] = 3;
                    break;
                default:
                    $info['gear'] = 0;
            }

            $order_where = [
                'user_id' => $user_id,
                'is_pay' => 1,
                'is_del' => 0,
                'back_order_sn' => ''
            ];
            // 待发货订单数量
            $wait_send_order_count = Db::name('order')->where($order_where)->where(['status' => 2])->count();
            // 待收货订单数量
            $wait_get_order_count = Db::name('order')->where($order_where)->where(['status' => 3])->count();
            // 待评价订单数量
            $wait_comment_order_count = Db::name('order')->where($order_where)->where(['status' => 4])->count();
            // 售后中订单数量
            $after_order_count = Db::name('order')->where($order_where)->where(['status' => 7])->count();
            // 待付款订单数量
            $order_where['is_pay'] = 0;
            $wait_pay_order_count = Db::name('order')->where($order_where)->where(['status' => 1])->count();

            $info['wait_pay_order_count'] = $wait_pay_order_count;
            $info['wait_send_order_count'] = $wait_send_order_count;
            $info['wait_get_order_count'] = $wait_get_order_count;
            $info['wait_comment_order_count'] = $wait_comment_order_count;
            $info['after_order_count'] = $after_order_count;

            $apply_shop_user_level = C('APPLY_SHOP_USER_LEVEL');
            $info['apply_shop_user_level'] = $apply_shop_user_level;
            $info['apply_shop_user_level_desc'] = doUserLevel($apply_shop_user_level);

            // 查询门店是否已经被禁用
            $shop_info = Db::name('shop')->field('disable,province,city,area')->where(['user_id' => $user_id])->find();
            $info['shop_disable'] = $shop_info['disable'];
            $info['shop_region'] = $shop_info['province'] . $shop_info['city'] . $shop_info['area'];

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '用户不存在或已禁用');
        }
    }

    /**
     * 获取某个用户的消费总额
     * @param int $user_id 用户id
     * @return float
     **/
    public function getMeConsume($user_id)
    {
        $consume = Db::name('order')->where(['user_id' => $user_id, 'is_pay' => 1, 'complete_time' => ['neq', 0]])->sum('pay_price');
        return sprintf('%.2f', $consume);
    }

    /**
     * 我的收益详情
     * */
    public function userProfit()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        // 自己消费总额
        $me_all_consume = $this->getMeConsume($user_id);

        // 总累计销售额 = 我和我的所有下线的消费统计
        $all_consume = $me_all_consume + action('Algorithm/Algorithm/allConsume', ['user_id' => $user_id]);
        /**
         * 个人零售销售额 = 自己消费总额中除去自己首次消费金额
         * */
        // 自己首次消费金额
        $first_consume = Db::name('order')->where(['user_id' => $user_id, 'is_pay' => 1, 'complete_time' => ['neq', 0]])->order('id asc')->value('pay_price');
        // 个人零售销售额 = 自己消费总额 - 自己首次消费金额
        $me_consume = sprintf('%.2f', $me_all_consume - $first_consume);

        $profit_where = [
            'user_id' => $user_id,
            'status' => ['neq', -1],
            'type' => ['IN', [1, 2, 3]]
        ];
        // 总累计收益
        $all_profit = Db::name('profit')->where($profit_where)->sum('price');
        // 可用收益
        $normal_profit = Db::name('user')->where(['id' => $user_id])->value('all_profit');
        // 冻结收益
        $frozen_profit = Db::name('profit')->where($profit_where)->where(['status' => 1])->sum('price');

        $info = [
            'all_consume' => sprintf('%.2f', $all_consume),
            'me_consume' => sprintf('%.2f', $me_consume),
            'all_profit' => sprintf('%.2f', $all_profit),
            'normal_profit' => sprintf('%.2f', $normal_profit),
            'frozen_profit' => sprintf('%.2f', $frozen_profit),
        ];

        apiReturn(1, '获取数据成功', $info);
    }

    /*public function test()
    {
        $user_arr = [1786, 1071, 1068, 1067];

        if ($user_arr) {
            foreach ($user_arr as &$val) {
                $user_id = $val;
                $profit_where = [
                    'user_id' => $user_id,
                    'status' => 2
                ];
                $profit_list = Db::name('profit')->field('id,order_id,user_id,type,price,remark,create_time')->where($profit_where)->order('create_time desc')->select();
                $all_price = 0;
                if ($profit_list) {
                    foreach ($profit_list as &$v) {
                        switch ($v['type']) {
                            case 2:
                            case 1:
                            case 3:
                            case 6:
                            case 7:
                            case 9:
                            case 8:
                            case 10:
                            case 12:
                                $all_price = $all_price + $v['price'];
                                break;
                            case 4:
                            case 5:
                            case 11:
                                $all_price = $all_price - $v['price'];
                                break;
                        }
                    }
                }

                $user_info = Db::name('user')->field('id,all_profit,username')->where(['id' => $user_id])->find();

                $str = 'ID：' . $user_id . '；用户：' . $user_info['username'] . '；收益累计计算可用收益：' . $all_price . '；可用收益字段显示：' . $user_info['all_profit'];

                file_put_contents(RUNTIME_PATH . 'profit.txt', $str . PHP_EOL . PHP_EOL, FILE_APPEND);
            }
        }
    }

    public function test2()
    {
        $user_id = Request()->param('user_id');

        $profit_where = [
            'user_id' => $user_id,
            'status' => ['neq', -1]
        ];
        $profit_list = Db::name('profit')->field('id,order_id,user_id,type,price,remark,create_time')->where($profit_where)->order('create_time desc')->select();
        $all_price = 0;
        if ($profit_list) {
            foreach ($profit_list as &$v) {
                switch ($v['type']) {
                    case 2:
                    case 1:
                    case 3:
                    case 6:
                    case 7:
                    case 9:
                    case 8:
                    case 10:
                    case 12:
                        $all_price = $all_price + $v['price'];
                        break;
                    case 4:
                    case 5:
                    case 11:
                        $all_price = $all_price - $v['price'];
                        break;
                }
            }
        }

        $user_info = Db::name('user')->field('id,all_profit,username')->where(['id' => $user_id])->find();

        $str = 'ID：' . $user_id . '；用户：' . $user_info['username'] . '；收益累计计算可用收益：' . $all_price . '；可用收益字段显示：' . $user_info['all_profit'];

        file_put_contents(RUNTIME_PATH . 'profit.txt', $str . PHP_EOL . PHP_EOL, FILE_APPEND);
    }

    public function editProfit()
    {
//        $user_arr = [1786, 1071, 1068, 1065, 1067];
//        revemo user id:1069,1078,1509,1089
        $user_arr = [1064,1065,1066,1067,1068,1070,1071,1072,1073,1074,1075,1076,1077,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,1100,1101,1102,1107,1110,1112,1113,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163,1164,1165,1166,1167,1168,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1179,1180,1181,1182,1183,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1195,1196,1197,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257,1258,1259,1260,1261,1262,1263,1264,1265,1266,1267,1268,1269,1270,1271,1272,1273,1274,1275,1276,1277,1278,1279,1280,1281,1282,1283,1284,1285,1286,1287,1288,1289,1290,1291,1292,1293,1294,1295,1296,1502,1503,1504,1510,1511,1512,1513,1514,1515,1516,1517,1518,1519,1520,1521,1522,1523,1524,1525,1526,1527,1528,1529,1530,1531,1532,1533,1534,1535,1536,1537,1538,1539,1540,1541,1542,1543,1544,1545,1546,1547,1548,1549,1550,1551,1552,1553,1554,1555,1556,1557,1558,1559,1560,1561,1562,1563,1564,1565,1566,1567,1568,1569,1570,1571,1572,1573,1574,1575,1576,1577,1578,1579,1580,1581,1582,1583,1584,1585,1586,1587,1588,1589,1590,1591,1592,1593,1594,1595,1596,1597,1598,1599,1600,1601,1602,1603,1604,1605,1606,1607,1608,1609,1610,1611,1612,1613,1614,1615,1616,1617,1618,1619,1620,1621,1622,1623,1624,1625,1626,1627,1628,1629,1630,1631,1632,1633,1634,1635,1636,1637,1638,1639,1640,1641,1642,1643,1644,1645,1646,1647,1648,1649,1650,1651,1652,1653,1654,1655,1656,1657,1658,1659,1660,1661,1662,1663,1664,1665,1666,1667,1668,1669,1670,1671,1672,1673,1674,1675,1676,1677,1678,1679,1680,1681,1682,1683,1684,1685,1686,1687,1688,1689,1690,1691,1692,1693,1694,1695,1696,1697,1698,1699,1700,1701,1702,1703,1704,1705,1706,1707,1708,1709,1710,1711,1712,1713,1714,1715,1716,1717,1718,1719,1720,1721,1722,1723,1724,1725,1726,1727,1728,1729,1730,1731,1732,1733,1734,1735,1736,1737,1738,1739,1740,1741,1742,1743,1744,1745,1746,1747,1748,1749,1750,1751,1752,1753,1754,1755,1756,1757,1758,1759,1760,1761,1762,1763,1764,1765,1766,1767,1768,1769,1770,1771,1772,1773,1774,1775,1776,1777,1778,1779,1780,1781,1782,1783,1784,1785,1786,1787,1788,1789,1790,1791,1792,1793,1794,1795,1796,1797,1798,1799,1800,1801,1802,1803,1804,1805,1806,1807,1808,1809,1810,1811,1812,1813,1814,1815,1816,1817,1818,1819,1820,1821,1822,1823,1824,1825,1826,1827,1828,1829,1830,1831,1832,1833,1834,1835,1836,1837,1838,1839,1840,1841,1842,1843,1844,1845,1846,1847,1848,1849,1850,1851,1852,1853,1854,1855,1856,1857,1858,1859,1860,1861,1862,1863,1864,1865,1866,1867,1868,1869,1870,1871,1872,1873,1874,1875,1876,1877,1878,1879,1880,1881,1882,1883,1884,1885,1886,1887,1888,1889,1890,1891,1892,1893,1894,1895,1896,1897,1898,1899,1900,1901,1902,1903,1904,1905,1906,1907,1908,1909,1910,1911,1912,1913,1914,1915,1916,1917,1918,1919,1920,1921,1922,1923,1924,1925,1926,1927,1928,1929,1930,1931,1932,1933,1934,1935,1936,1937,1938,1939,1940,1941,1942,1943,1944,1945,1946,1947,1948,1949,1950,1951,1952,1953,1954,1955,1956,1957,1958,1959,1960,1961,1962,1963,1964,1965,1966,1967,1968,1969,1970,1971,1972,1973,1974,1975,1976,1977,1978,1979,1980,1981,1982,1983,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003];
//        $user_arr = Db::name('user')->select();
//        $user_arr = array_column($user_arr, 'id');
//        echo "<pre>";
//        print_r(implode(',', $user_arr));
//        exit;

        if ($user_arr) {
            foreach ($user_arr as &$val) {
                $user_id = $val;

                $profit_where = [
                    'user_id' => $user_id,
                    'status' => 2
                ];
                $profit_list = Db::name('profit')->field('id,order_id,user_id,type,price,remark,create_time')->where($profit_where)->order('create_time asc')->select();
                if ($profit_list) {
                    $all_price = 0;
                    foreach ($profit_list as &$v) {
                        switch ($v['type']) {
                            case 2:
                            case 1:
                            case 3:
                            case 6:
                            case 7:
                            case 9:
                            case 8:
                            case 10:
                            case 12:
                                $all_price = $all_price + $v['price'];
                                break;
                            case 4:
                            case 5:
                            case 11:
                                $all_price = ($all_price - $v['price'] > 0) ? $all_price - $v['price'] : 0;
                                break;
                        }
                    }
                }

                $user_info = Db::name('user')->field('id,username,all_profit,level')->where(['id' => $user_id])->find();

                // 自己消费总额
                $me_all_consume = $this->getMeConsume($user_id);
                // 总累计销售额 = 我和我的所有下线的消费统计
                $all_consume = $me_all_consume + action('Algorithm/Algorithm/allConsume', ['user_id' => $user_id]);

                $all_price = sprintf('%.2f', $all_price);

                if ($user_info['all_profit'] != $all_price && $user_info['all_profit'] > 0 && $all_consume > 0 && $user_info['level'] > 1){
                    $str = 'ID：' . $user_id . '；用户：' . $user_info['username'] . '；修正前可用收益：' . $user_info['all_profit'] . '；修正后可用收益：' . $all_price;
                }

                file_put_contents(RUNTIME_PATH . '收益修正记录.txt', $str . PHP_EOL . PHP_EOL, FILE_APPEND);

                Db::name('user')->where(['id' => $user_id])->setField('all_profit', $all_price);
            }
        }
    }

    public function zeroLog()
    {
        $list = Db::name('user')->where(['all_profit' => ['gt', 0]])->select();
        if($list){
            foreach($list as &$v){
                $count = Db::name('profit')->where(['user_id' => $v['id']])->count();
                if($count == 0){
                    $user_id = $v['id'];
//                    // 自己消费总额
//                    $me_all_consume = $this->getMeConsume($user_id);
//                    // 总累计销售额 = 我和我的所有下线的消费统计
//                    $all_consume = $me_all_consume + action('Algorithm/Algorithm/allConsume', ['user_id' => $user_id]);
//
//                    $user_info = Db::name('user')->field('id,username,all_profit,level')->where(['id' => $user_id])->find();

//                    file_put_contents(RUNTIME_PATH . 'ZERO.txt', '用户名：' . $user_info['username'] . '；消费金额：'. $all_consume .'；可用收益：' . $user_info['all_profit'] . PHP_EOL . PHP_EOL, FILE_APPEND);

                    Db::name('user')->where(['id' => $user_id])->setField('all_profit', 0);

                }
            }
        }
    }*/


    /**
     * 收益明细
     * */
    public function profitList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $profit_where = [
            'user_id' => $user_id,
            'status' => ['neq', -1]
        ];
        $profit_list = Db::name('profit')->field('id,order_id,user_id,type,price,remark,create_time')->where($profit_where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($profit_list) {
            foreach ($profit_list as &$v) {
                if ($v['type'] == 1 || $v['type'] == 2 || $v['type'] == 3) {
                    $pay_user_id = Db::name('order')->where(['id' => $v['order_id']])->value('user_id');
                    if ($pay_user_id) {
                        $user_info = Db::name('user')->field('username,gender')->where(['id' => $pay_user_id])->find();
                        $username = cutSubstr($user_info['username']);
                        if (mb_strlen($username) > 6) $username = cutSubstr($username, 6);
                    }
                } else {
                    $username = '';
                }

                switch ($v['type']) {
                    case 2:
                    case 1:
                        $desc = ' 成功购买了商品';
                        $change = 'plus';
                        break;
                    case 3:
                        $desc = '消费，您获得服务津贴';
                        $change = 'plus';
                        break;
                    case 4:
                        $desc = '购物收益抵扣';
                        $change = 'minus';
                        break;
                    case 5:
                        $desc = '收益提现';
                        $change = 'minus';
                        break;
                    case 6:
                    case 7:
                    case 9:
                        $desc = $v['remark'];
                        $change = 'plus';
                        break;
                    case 8:
                        $desc = '收益提现审核失败，收益返还';
                        $change = 'plus';
                        break;
                    case 10:
                        $desc = '充值收益';
                        $change = 'plus';
                        break;
                    case 11:
                        $desc = '处罚收益';
                        $change = 'minus';
                        break;
                    case 12:
                        $desc = '购物抵扣收益退款';
                        $change = 'plus';
                        break;
                }

                $v['username'] = $username;
                $v['desc'] = $desc;
                $v['change'] = $change;

                $v['create_time'] = timeFormat($v['create_time']);
            }
            apiReturn(1, '获取数据成功', $profit_list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 提现记录
     * */
    public function withdrawalList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('withdrawal')->field('id,real_price price,type,status,create_time')->where(['user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['desc'] = $v['status'] == 1 ? '提现到' . ($v['type'] == 1 ? '微信钱包' : '银行卡') : '提现审核失败';
                $v['change'] = $v['status'] == 1 ? 'plus' : 'minus';
                $v['create_time'] = timeFormat($v['create_time']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 提现页面数据回显
     * */
    public function withdrawalInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $user_info = Db::name('user')->field('id,all_profit,real_name,bank_name,bank_num,bank_deposit')->where(['id' => $user_id])->find();

        $empty_bank = ['请选择'];
        $bank_list = C('BANK_LIST');
        $bank_list = array_merge($empty_bank, $bank_list);
        $bankIndex = 0;
        if ($bank_list) {
            foreach ($bank_list as $k => &$v) {
                if ($user_info['bank_name'] == $v) {
                    $bankIndex = $k;
                    break;
                }
            }
        }

        $withdrawal_price = C('WITHDRAWAL_PRICE');

        $service_rate = C('SERVICE_RATE');

        $data = [
            'user_info' => $user_info,
            'bank_list' => $bank_list,
            'bankIndex' => $bankIndex,
            'withdrawal_price' => $withdrawal_price,
            'service_rate' => $service_rate
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 申请提现
     * */
    public function applyWithdrawal()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $price = $input['price'];
        $service_rate = $input['service_rate'];
        $real_price = $input['real_price'];
        $real_name = $input['real_name'];
        $bank_name = $input['bank_name'];
        $bank_num = $input['bank_num'];
        $bank_deposit = $input['bank_deposit'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($price)) apiReturn(2, '请输入提现金额');
        if (empty($real_price)) apiReturn(2, '实际到账金额错误');

        $user_info = Db::name('user')->where(['id' => $user_id])->find();
        if ($price > $user_info['all_profit']) apiReturn(2, '提现金额超出当前可提');

        $time = time();

        $withdrawal_price = C('WITHDRAWAL_PRICE');

        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(date('Y-m-d')) + 24 * 3600 - 1;
        $count = Db::name('withdrawal')->where(['user_id' => $user_id, 'status' => ['neq', 2], 'create_time' => ['between', [$start_time, $end_time]]])->count();
        if ($count) apiReturn(2, '每号每天限提一次');

        Db::startTrans();
        try {

            $order_sn = uniqid();                //订单号

            if ($price <= $withdrawal_price) {
                if (empty($user_info['openid'])) apiReturn(2, 'openid缺失');

                // 提现到微信零钱
                $mchid = C('MCH_ID');          //微信支付商户号 PartnerID 通过微信支付商户资料审核后邮件发送
                $appid = C('XCX_APPID');       //微信支付申请对应的公众号的APPID
                $appKey = C('XCX_SECRET');     //微信支付申请对应的公众号的APP Key
                $apiKey = C('MCH_KEY');        //https://pay.weixin.qq.com 帐户设置-安全设置-API安全-API密钥-设置API密钥

                Loader::import('weixinPay\weixinPay-master\transfers', EXTEND_PATH);
                $obj = new \WxpayService($mchid, $appid, $appKey, $apiKey);

                $obj->createJsBizPackage($user_info['openid'], $price, $order_sn, $real_name);

                $data = [
                    'order_sn' => $order_sn,
                    'user_id' => $user_id,
                    'price' => $price,
                    'type' => 1,
                    'create_time' => $time
                ];
                Db::name('withdrawal')->insert($data);
            } else {
                if (empty($real_name) || $real_name == 'undefined') apiReturn(2, '姓名信息异常，请重新输入');
                if (empty($bank_name) || $bank_name == 'undefined' || $bank_name == '请选择') apiReturn(2, '请选择银行');
                if (empty($bank_num) || $bank_num == 'undefined') apiReturn(2, '银行卡号信息异常，请重新输入');
                if (empty($bank_deposit) || $bank_deposit == 'undefined') apiReturn(2, '开户行信息异常，请重新输入');

                // 申请提现到银行卡
                $data = [
                    'order_sn' => $order_sn,
                    'user_id' => $user_id,
                    'price' => $price,
                    'rate' => $service_rate,
                    'service_price' => $price - $real_price,
                    'real_price' => $real_price,
                    'type' => 2,
                    'real_name' => $real_name,
                    'bank_name' => $bank_name,
                    'bank_num' => $bank_num,
                    'bank_deposit' => $bank_deposit,
                    'create_time' => $time
                ];
                Db::name('withdrawal')->insert($data);
            }

            $user_data = [
                'all_profit' => $user_info['all_profit'] - $price,
                'real_name' => $real_name,
                'bank_name' => $bank_name,
                'bank_num' => $bank_num,
                'bank_deposit' => $bank_deposit
            ];
            Db::name('user')->where(['id' => $user_id])->update($user_data);

            Db::commit();
            apiReturn(1, '申请提现成功');
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~' . $e);
        }
    }

    /**
     * 订单列表
     * */
    public function orderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['user_id'] = $user_id;
        $where['is_del'] = 0;
        if ($status) $where['status'] = $status;
        $list = Db::name('order')->field('id,order_sn,pay_price,status')->where($where)->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['status_desc'] = doOrderStatus($v['status']);

                $goods_list = Db::name('vice_order')->field('id,img,name,price,count,sku_id')->where(['order_id' => $v['id']])->select();
                if ($goods_list) {
                    foreach ($goods_list as &$val) {
                        $val['img'] = getPicture($val['img']);
                        if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));
                    }
                    $v['goods_list'] = $goods_list;
                }
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 订单详情
     * */
    public function orderDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '订单ID缺失');

        $info = Db::name('order')->field('id,order_sn,all_price,freight_price,coupon_id,remark,pay_price,status,pay_type,express_id,send_num,get_username,get_mobile,get_province,get_city,get_area,get_address,create_time')->where(['id' => $id])->find();
        if ($info) {
            $info['create_time'] = timeFormat($info['create_time'], 'Y.m.d H:i:s');
            $info['status_desc'] = doOrderStatus($info['status']);

            $coupon_price = 0;
            if ($coupon_id = $info['coupon_id']) $coupon_price = Db::name('user_coupon')->where(['id' => $coupon_id])->value('face_price');
            $info['coupon_price'] = sprintf('%.2f', $coupon_price);

            if ($express_id = $info['express_id']) $info['express_name'] = Db::name('express')->where(['id' => $express_id])->value('name');

            $goods_list = Db::name('vice_order')->field('id,goods_id,img,name,price,count,sku_id,gift_ids')->where(['order_id' => $id])->select();
            if ($goods_list) {
                foreach ($goods_list as &$val) {
                    $val['img'] = getPicture($val['img']);
                    if ($sku_list = getSkuName(explode('-', $val['sku_id']))) $val['sku'] = implode('，', array_column($sku_list, 'name'));

                    $gift_list = [];
                    if ($val['gift_ids']) $gift_list = Db::name('goods_gift')->field('id,gift_img,gift_name,gift_price')->where(['id' => ['IN', $val['gift_ids']], 'is_del' => 0, 'start_date' => ['elt', date('Y-m-d')], 'end_date' => ['egt', date('Y-m-d')]])->select();
                    if ($gift_list) {
                        foreach ($gift_list as &$value) {
                            $value['gift_img'] = getPicture($value['gift_img']);
                        }
                    }
                    $val['gift_list'] = $gift_list;
                }

                $info['goods_list'] = $goods_list;
            }

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '订单不存在或已删除');
        }
    }

    /**
     * 信息设置回显数据
     * */
    public function userInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $user_info = Db::name('user')->field('id,avatar,username,gender,birthday,mobile')->where(['id' => $user_id])->find();
        if ($user_info) {
            $user_info['avatar_path'] = doAvatar($user_info['avatar']);
            $user_info['hide_mobile'] = hideMobile($user_info['mobile']);

            $address_info = Db::name('address')->field('province_id,city_id,area_id')->where(['user_id' => $user_id])->order('is_default desc')->find();
            if ($address_info) {
                $address = getProvinceName($address_info['province_id']) . getCityName($address_info['city_id']) . getAreaName($address_info['area_id']);
                $user_info['address'] = $address;
            } else {
                $user_info['address'] = '';
            }

            apiReturn(1, '获取数据成功', $user_info);
        } else {
            apiReturn(2, '用户信息不存在或已禁用');
        }
    }

    /**
     * 保存用户信息
     * */
    public function saveUserInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $avatar = $input['avatar'];
        $username = $input['username'];
        $gender = $input['gender'];
        $birthday = $input['birthday'];
        $mobile = $input['mobile'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($avatar)) apiReturn(2, '请上传头像');
        if (empty($username)) apiReturn(2, '请输入昵称');

        $info = Db::name('user')->where(['id' => $user_id])->find();

        // 游客（绑定手机号+有上级）自动升级成VIP
        $level = ($mobile && $info['level'] == 1 && $info['up_user_id'] > 0) ? 2 : $info['level'];
        if ($info) {
            $data = [
                'avatar' => $avatar,
                'username' => $username,
                'gender' => $gender,
                'birthday' => $birthday,
                'mobile' => $mobile,
                'level' => $level,
                'update_time' => time()
            ];

            $res = Db::name('user')->where(['id' => $user_id])->update($data);
            if ($res) {
                apiReturn(1, '保存成功');
            } else {
                apiReturn(2, '保存失败');
            }
        } else {
            apiReturn(2, '用户不存在或已删除');
        }
    }

    /**
     * 收货地址详情
     * */
    public function addressDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '收货地址ID缺失');

        $info = Db::name('address')->field('id,username,mobile,province_id,city_id,area_id,address,is_default')->where(['id' => $id])->find();
        if ($info) {
            $info['region'] = [getProvinceName($info['province_id']), getCityName($info['city_id']), getAreaName($info['area_id'])];
            $info['defaultIndex'] = $info['is_default'] == 1 ? 0 : 1;

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '收货地址不存在或已删除');
        }
    }

    /**
     * 添加收货地址
     * */
    public function addAddress()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $username = $input['username'];
        $mobile = $input['mobile'];
        $province_code = $input['province_code'];
        $city_code = $input['city_code'];
        $area_code = $input['area_code'];
        $address = $input['address'];
        $is_default = $input['is_default'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($province_code) || empty($city_code) || empty($area_code) || empty($address)) apiReturn(2, '请完善收货地址');
        if (empty($username)) apiReturn(2, '请填写收货人姓名');
        if (empty($mobile)) apiReturn(2, '请填写联系方式');

        if ($is_default == 1) {
            //查询默认的收货地址
            $default_info = Db::name('address')->where(['user_id' => $user_id, 'is_default' => 1])->find();
        } else {
            //查询是不是第一个收货地址，是第一个收货地址的话，就设置成默认的
            $count = Db::name('address')->where(['user_id' => $user_id])->count();
            if ($count == 0) $is_default = 1;
        }

        $data = [
            'user_id' => $user_id,
            'username' => $username,
            'mobile' => $mobile,
            'province_id' => $province_code,
            'city_id' => $city_code,
            'area_id' => $area_code,
            'address' => $address,
            'is_default' => $is_default,
            'create_time' => time()
        ];
        $res = Db::name('address')->insert($data);
        if ($res) {
            Db::name('address')->where(['id' => $default_info['id']])->setField('is_default', 0);
            apiReturn(1, '添加成功');
        } else {
            apiReturn(2, '添加失败');
        }
    }

    /**
     * 编辑收货地址
     * */
    public function editAddress()
    {
        $input = Request()->param();

        $id = $input['id'];
        $username = $input['username'];
        $mobile = $input['mobile'];
        $province_code = $input['province_code'];
        $city_code = $input['city_code'];
        $area_code = $input['area_code'];
        $address = $input['address'];
        $is_default = $input['is_default'];

        if (empty($id)) apiReturn(2, '收货地址ID缺失');
        if (empty($province_code) || empty($city_code) || empty($area_code) || empty($address)) apiReturn(2, '请完善收货地址');
        if (empty($username)) apiReturn(2, '请填写收货人姓名');
        if (empty($mobile)) apiReturn(2, '请填写联系方式');

        //查询默认的收货地址
        $default_info = Db::name('address')->where(['id' => $id])->find();
        $data = [
            'username' => $username,
            'mobile' => $mobile,
            'province_id' => $province_code,
            'city_id' => $city_code,
            'area_id' => $area_code,
            'address' => $address,
            'is_default' => $is_default,
            'update_time' => time()
        ];
        $res = Db::name('address')->where(['id' => $id])->update($data);
        if ($res) {
            if ($is_default == 1) {
                if ($default_info['is_default'] != 1) {
                    //将原来的默认收货地址修改成非默认
                    Db::name('address')->where(['user_id' => $default_info['user_id'], 'is_default' => 1, 'id' => ['neq', $id]])->setField('is_default', 0);
                }
            }
            apiReturn(1, '编辑成功');
        } else {
            apiReturn(2, '编辑失败');
        }
    }

    /**
     * 删除收货地址
     * */
    public function delAddress()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (empty($id)) apiReturn(2, '收货地址ID缺失');

        $info = Db::name('address')->where(['id' => $id])->find();
        if ($info) {
            $res = Db::name('address')->where(['id' => $id])->delete();
            if ($res) {
                apiReturn(1, '删除成功');
            } else {
                apiReturn(2, '删除失败');
            }
        } else {
            apiReturn(2, '收货地址不存在或已删除');
        }
    }

    /**
     * 我的券包
     * */
    public function couponList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $status = $input['status'] ? : 0;
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $where['user_id'] = $user_id;
        $where['is_del'] = 0;
        if ($status) $where['status'] = $status;

        $list = Db::name('user_coupon')->field('id,coupon_name,full_price,face_price,expire_time,status,create_time')->where($where)->order('status asc,expire_time asc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['expire_time'] = str_replace('-', '.', $v['expire_time']);
                $v['desc'] = '限' . timeFormat($v['create_time'], 'Y.m.d') . '-' . $v['expire_time'] . '期间使用';
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 我的收藏
     * */
    public function collectList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('collect c')
            ->join('shop_goods g', 'c.to_id = g.id', 'left')
            ->field('g.id,g.img,g.name,g.min_price,g.min_vip_price')
            ->where(['user_id' => $user_id, 'type' => 1, 'status' => 1])
            ->page($page, $pagesize)
            ->select();

        if ($list) {
            $user_level = Db::name('user')->where(['id' => $user_id])->value('level');

            foreach ($list as &$v) {
                $price = $user_level > 1 ? $v['min_vip_price'] : $v['min_price'];
                $v['price'] = sprintf('%.2f', $price);
                $v['img'] = getPicture($v['img']);
            }

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 我的分享
     * */
    public function getShareData()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        //分享二维码
        /*$qr = Db::name('user')->where(['id' => $user_id])->value('qr');
        if (!$qr) {
            $qr = createUserQr($user_id);
        }
        $qr = getPicture($qr);*/

        // 顾客总数：形成上下级关系
        $bind_user_count = Db::name('user')->where(['up_user_id' => $user_id])->count();

        // 成功分享：已激活的总数
        $success_user_count = Db::name('user')->where(['up_user_id' => $user_id, 'is_activation' => 1])->count();

        // 今日新增
        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(date('Y-m-d')) + 24 * 3600 - 1;
        $today_bind_user_count = Db::name('user')->where(['up_user_id' => $user_id, 'create_time' => ['between', [$start_time, $end_time]]])->count();

        $data = [
            'qr' => $qr,
            'bind_user_count' => $bind_user_count,
            'success_user_count' => $success_user_count,
            'today_bind_user_count' => $today_bind_user_count,
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 我的分享顾客列表
     * */
    public function shareUserList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $page = $input['page'] ? : 1;
        $pagesize = $input['pagesize'] ? : 10;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('user')->field('id,username,avatar,mobile,is_activation,create_time')->where(['up_user_id' => $user_id])->order('create_time desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = doAvatar($v['avatar']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y-m-d');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据', []);
        }
    }

    /**
     * 用户门店信息
     * */
    public function userShop()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');


        $info = Db::name('shop')->where(['user_id' => $user_id])->find();
        if ($info) {
            $info['region'] = $info['province'] . ' - ' . $info['city'] . ' - ' . $info['area'];
            $info['yyzz_img_path'] = getPicture($info['yyzz_img']);
            $shop_imgs = doImgs($info['shop_imgs']);
        }

        $region_list = Db::name('shop_region')->field('id,province,city,area')->select();
        $region_index = 0;
        if ($region_list) {
            foreach ($region_list as $k => &$v) {
                $v['region'] = $v['province'] . ' - ' . $v['city'] . ' - ' . $v['area'];
                if ($v['region'] == $info['province'] . ' - ' . $info['city'] . ' - ' . $info['area']) $region_index = $k + 1;
                unset($v['province']);
                unset($v['city']);
                unset($v['area']);
            }
        } else {
            $region_list = [];
        }

        $info['name'] = $info['name'] ? : '';
        $info['status'] = $info['status'] ? : 0;

        $data = [
            'info' => $info,
            'imgs' => $shop_imgs,
            'imgs_id' => $info['shop_imgs'],
            'region_list' => $region_list,
            'region_index' => $region_index
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 保存门店信息
     * */
    public function saveShop()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];
        $name = $input['name'];
        $region = $input['region'];
        $yyzz_img = $input['yyzz_img'];
        $shop_imgs = $input['shop_imgs'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($name)) apiReturn(2, '请输入门店名称');
        if (empty($region)) apiReturn(2, '请选择门店地址');
        if (empty($yyzz_img)) apiReturn(2, '请上传营业执照');
        if (empty($shop_imgs)) apiReturn(2, '请上传门店照片');

        $level = Db::name('user')->where(['id' => $user_id])->value('level');
        if ($level < C('APPLY_SHOP_USER_LEVEL')) apiReturn(2, '达到' . doUserLevel(C('APPLY_SHOP_USER_LEVEL')) . '才可以申请门店');

        $region_info = explode(' - ', $region);

        $time = time();
        $data = [
            'user_id' => $user_id,
            'name' => $name,
            'province' => $region_info[0],
            'city' => $region_info[1],
            'area' => $region_info[2],
            'yyzz_img' => $yyzz_img,
            'shop_imgs' => $shop_imgs,
            'status' => 0
        ];

        if ($id) {
            $data['update_time'] = $time;

            $res = Db::name('shop')->where(['id' => $id])->update($data);
        } else {
            $data['create_time'] = $time;

            $res = Db::name('shop')->insert($data);
        }
        if ($res) {
            apiReturn(1, '提交成功');
        } else {
            apiReturn(2, '提交失败');
        }
    }

    /**
     * 意见反馈
     * */
    public function addFeedback()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $content = $input['content'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');
        if (empty($content)) apiReturn(2, '请输入反馈意见');

        checkContent($content);

        $data = [
            'user_id' => $user_id,
            'content' => $content,
            'create_time' => time()
        ];

        $res = Db::name('feedback')->insert($data);
        if ($res) {
            apiReturn(1, '反馈成功');
        } else {
            apiReturn(2, '反馈失败');
        }
    }

    /**
     * 关于我们
     * */
    public function aboutUs()
    {
        $content = Db::name('about_us')->where(['id' => 1])->value('content');

        $content = doEditorContent($content);

        apiReturn(1, '获取数据成功', $content);
    }

}
